from flask import Blueprint, jsonify, request
import json
from datab import datab
import math

bp_cate = Blueprint('cate', __name__)


@bp_cate.route('/cate', methods=['POST', 'GET'])
def cate():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into qcate values (%d,"%s") """ % (0, data['name'])
        datab.use_db(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = """select * from qcate"""
        res = datab.findall(sql)
        return jsonify({"code": 200, 'list': res})


@bp_cate.route('/shop', methods=['POST', 'GET', 'DELETE'])
def shop():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into qshop values (%d,"%s",%d) """ % (0, data['name'], int(data['cid']))
        datab.use_db(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        cpage = int(request.args.get('cpage'))
        print(cpage)
        size = 3
        start = ((cpage - 1) * size)
        sql = '''select s.id,s.name,s.cid,c.name as cname from qshop as s left join qcate as c on s.cid=c.id order by id desc limit %d,%d''' % (
            start, size)
        res = datab.findall(sql)
        sql2 = '''select count(id) from qshop'''
        res2 = datab.findone(sql2)
        total = math.ceil(res2["count(id)"] / size)

        return jsonify({'code': 200, 'list': res, 'total': total})
    elif request.method == 'DELETE':
        id = int(request.args.get('id'))
        sql = '''delete from qshop where id = %d''' % (id)
        datab.use_db(sql)
        return jsonify({"code": 200})


@bp_cate.route('/shop1', methods=['GET', 'DELETE'])
def shop1():
    if request.method == 'GET':
        id = request.args.get('id')
        sql = '''select s.id,s.name,s.cid,c.name as cname from qshop as s left join qcate as c on s.cid = c.id where c.id = %d order by id desc ''' % (
            int(id))
        res = datab.findall(sql)
        return jsonify({'code': 200, 'list': res})
    elif request.method == 'DELETE':
        list = request.args.get('list')
        sql = '''delete from qshop where id in (%s) ''' % (list)
        datab.use_db(sql)
        return jsonify({"code": 200})
